/*
 * @Description: 真实性格式设置弹窗
 * @Author: Rfan
 * @Date: 2022-10-10 20:45:23
 * @LastEditTime: 2022-10-17 11:24:44
 */

import { useEffect, useState } from 'react';
import { Checkbox, Form, Select, Space } from 'antd';
import classnames from 'classnames/bind';
import { selectItemByKey } from '@/utils/list';
import { useAddPlanDialogContext } from '../../../../../contexts/AddPlanDialogContext';
import { EnumCheckContentType, EnumFieldCheckType } from '../../../../../../../../dictionaries';
import type { Callbacks } from 'rc-field-form/lib/interface';
import type { IBaseDic } from '@/interfaces/global';
import type { IRuleSetting } from '@/view/system/ArchivesDetection/interface';
import styles from '../../../../../styles/entryPanes.module.scss';
import { IPropsRuleWithSetting } from '@/view/system/ArchivesDetection/interface';

const cx = classnames.bind(styles);
const { Option } = Select;

interface IFieldTypeProps {
  data: any;
  onChange: any;
}

const FieldType = (props: IFieldTypeProps) => {
  const { data, onChange } = props;
  const { metadataTypeList } = useAddPlanDialogContext();
  const [form] = Form.useForm();

  // 格式检测数据
  const [ruleData, setRuleData] = useState<IPropsRuleWithSetting<EnumFieldCheckType>>({
    ruleType: EnumFieldCheckType.Type,
    ruleValid: false,
    rule: {
      contentType: EnumCheckContentType.Regular,
      content: metadataTypeList[0].id
    }
  });

  useEffect(() => {
    if (data?.rules) {
      const lengthData = selectItemByKey(EnumFieldCheckType.Type, data.rules, 'ruleType');
      if (lengthData && lengthData?.rule?.content >= 0) {
        setRuleData(lengthData);
      }
    }
  }, [data]);

  useEffect(() => {
    form.setFieldsValue({ ...ruleData.rule, ruleValid: ruleData.ruleValid });
  }, [ruleData]);

  const changeFormFunc: Callbacks['onValuesChange'] = (_changeVal, values) => {
    const fieldRuleType = EnumFieldCheckType.Type;
    const rule = { ...values, contentType: EnumCheckContentType.Regular };
    delete rule.ruleValid;

    const editLengthObj = {
      ruleType: fieldRuleType,
      ruleValid: values.ruleValid,
      rule
    };
    onChange(data.key, fieldRuleType, editLengthObj);
  };

  return (
    <Form
      form={form}
      className={cx('field-type')}
      layout="inline"
      size="small"
      onValuesChange={changeFormFunc}
    >
      <Space size="small">
        <Form.Item name="ruleValid" valuePropName="checked">
          <Checkbox />
        </Form.Item>
        <Form.Item name="content">
          <Select className={cx('type--content')}>
            {metadataTypeList.map((type: IBaseDic) => (
              <Option key={type.id} value={type.id}>
                {type.name}
              </Option>
            ))}
          </Select>
        </Form.Item>
      </Space>
    </Form>
  );
};

export default FieldType;
